package lium.lbs.lbsim.utils;

import android.util.Base64;
import android.util.Log;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * DES加密 解密算法
 *
 * @author lifq
 * @date 2015-3-17 上午10:12:11
 */
public class DesUtils {

    public static String main(String args) throws Exception {
        String keyText = "niubidek";

//	       plainText = "miki西游| mikixiyou@126.com";
//	       keyText ="abcd1234";


        String encryptedString = encryptDESwithBase64(args, keyText);
//        String encryptedString123 =decryptDESwithBase64(encryptedString, keyText);


        System.out.println("明文：" + args);
        System.out.println("密钥：" + keyText);
        System.out.println("密文：" + encryptedString);
//        System.out.println("123：" + encryptedString123);
        Log.e("post", args + "-----------" + keyText + "-----" + encryptedString);
        return encryptedString;
    }


    private static byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8};

    public static byte[] encryptDES(String encryptString, String encryptKey)
            throws Exception {

        System.out.println("willencryptedData with UTF-8 encoding =" + parseByte2HexStr(encryptString.getBytes("UTF-8")));

        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes("UTF-8"));
        System.out.println("didencryptedData  =" + parseByte2HexStr(encryptedData));
        return encryptedData;
    }

    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static String encryptDESwithBase64(String encryptString, String encryptKey) throws Exception {
        return new String(Base64.encode(encryptDES(encryptString, encryptKey),Base64.DEFAULT));
    }


}
